<?php

/**
 * This is the model class for table "post_image".
 *
 * The followings are the available columns in table 'post_image':
 * @property integer $id
 * @property integer $post_id
 * @property string $path
 * @property integer $featured
 * @property string $created_at
 * @property string $updated_at
 */
class PostImage extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return PostImage the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'post_image';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('post_id, featured', 'numerical', 'integerOnly' => true),
            array('path', 'length', 'max' => 255),
            array('featured', 'default', 'value' => 0),
            array('created_at, updated_at', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, post_id, path, featured, created_at, updated_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * set timestamp before save
     */
    public function beforeSave() {
        if ($this->isNewRecord)
            $this->created_at = new CDbExpression('NOW()');
        $this->updated_at = new CDbExpression('NOW()');
        return parent::beforeSave();
    }

    /**
     * delete uploaded images after delete model
     */
    public function afterDelete() {
        $path = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . $this->path;
        unlink($path);
        return parent::afterDelete();
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'post' => array(self::BELONGS_TO, 'Post', 'post_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => Yii::t('post', 'id'),
            'post_id' => Yii::t('post', 'postId'),
            'path' => Yii::t('post', 'path'),
            'featured' => Yii::t('post', 'featuredImage'),
            'created_at' => Yii::t('post', 'createdAt'),
            'updated_at' => Yii::t('post', 'updatedAt'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('post_id', $this->post_id);
        $criteria->compare('path', $this->path, true);
        $criteria->compare('featured', $this->featured);
        $criteria->compare('created_at', $this->created_at, true);
        $criteria->compare('updated_at', $this->updated_at, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    /**
     * get all images path
     */
    public function getAllImagesPath() {
        $postImages = PostImage::model()->findAll();
        $paths = array();
        foreach ($postImages as $postImage) {
            $paths[] = $postImage->path;
        }
        return $paths;
    }

    /**
     * check existed image path 
     */
    public function existedImagePath($path) {
        $result = false;
        try {
            $postImages = PostImage::model()->findAll();
            foreach ($postImages as $postImage) {
                if ($postImage->path == $path) {
                    $result = true;
                    break;
                }
            }
        } catch (Exception $ex) {
            $result = true;
            echo $ex->getMessage();
        }
        return $result;
    }

    /**
     * delete all product images by product_id
     */
    public function deleteAllByPostID($id) {
        $criteria = new CDbCriteria;
        $criteria->condition = "post_id =:post_id";
        $criteria->params = array(':post_id' => $id);
        return PostImage::model()->deleteAll($criteria);
    }

    /**
     * delete all ProductImage by Product
     * 
     */
    public function deleteAllByPost($post) {
        $postImages = $post->postImages;
        foreach ($postImages as $postImage) {
            $deleted = $postImage->delete();
            /* if ($deleted) {
              $path = Yii::getPathOfAlias('webroot.images') . DIRECTORY_SEPARATOR . $productImage->path;
              unlink($path);
              } */
        }
    }

}